package tv.youxing.android;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.Pools;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.client.ProgressListener;
import com.kymjs.rxvolley.http.VolleyError;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okserver.OkDownload;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.youxing.android.application.BaseApplication;
import tv.youxing.android.custom.ClickImageView;
import tv.youxing.android.custom.CommonProgressDialog;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.APKInfoDesModel;
import tv.youxing.android.entity.VideoPlayerPostModel;
import tv.youxing.android.fragment.FriendFragment;
import tv.youxing.android.fragment.HomepageFragment;
import tv.youxing.android.fragment.MineFragment;
import tv.youxing.android.fragment.SubscribeFragment;
import tv.youxing.android.ui.BaseActivity;
import tv.youxing.android.ui.SubscribeDeteilsActivity;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;


public class MainActivity extends BaseActivity implements View.OnClickListener {


    APKInfoDesModel mAPKInfoDesModel;
    private CommonProgressDialog pBar;


    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List<String> mTitle;
    private List<Integer> mIcon;
    private List<Fragment> mFragment;
    private ImageButton mPlayBtn;


    private View datelayout;
    private View findlayout;
    private View setupolayout;
    private View messagelayout;


    RelativeLayout home;
    RelativeLayout sub;
    RelativeLayout fri;
    RelativeLayout mine;


    private ClickImageView one1;
    private ClickImageView two1;
    private ClickImageView three1;
    private ClickImageView four1;

    private HomepageFragment showdate;
    private SubscribeFragment showfind;
    private FriendFragment showsetup;
    private MineFragment showmessage;

    private FragmentManager frangementmanager; //用于对fragement处理

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        getScreenSize();
        initData();
        initView();


//        initWindow();


        // 自定义颜色
//        tintManager.setTintColor(Color.parseColor("#00000000"));


    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        //按back键activity保留在后台不销毁
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            moveTaskToBack(true);
//            return true;
//        }


        //按back弹出是否退出
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                CustomToast.INSTANCE.showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }


        //按home键activity保留在后台不销毁
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            moveTaskToBack(true);
            return true;
        }




        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //注释掉 保证fragment不会反复创建
//        super.onSaveInstanceState(outState);
    }

    @OnClick({R.id.home, R.id.subscribe})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.home:
                System.out.println("home");
                break;
            case R.id.subscribe:
                System.out.println("subscribe");
                break;
        }
    }


    /**
     * 获取屏幕分辨率
     */
    private void getScreenSize() {
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

        ShareUtils.putInt(this, "width", width);
        ShareUtils.putInt(this, "height", height);
    }

    private void initData() {

        removeLoginActivitys();//清除之前所有的主页面

        System.out.println("token:" + ShareUtils.getString(this, AppConst.TOKEN, ""));
        System.out.println("userid:" + ShareUtils.getInt(this, AppConst.USERID, 0));



        Logger.d("token:" + ShareUtils.getString(this, AppConst.TOKEN, ""));

        //从数据库中恢复下载记录数据
        List<Progress> progressList = DownloadManager.getInstance().getAll();
        OkDownload.restore(progressList);


        //检查APP更新
        checkUpdate();
    }




    private void initView() {

        ShareUtils.putString(this,AppConst.PhoneDeviceBrand, UtilTools.getDeviceBrand());
        ShareUtils.putString(this,AppConst.PhoneSystemModel, UtilTools.getSystemModel());


//        System.out.println("手机厂商:" + UtilTools.getDeviceBrand());
//        System.out.println("手机型号:" + UtilTools.getSystemModel());


        mPlayBtn = (ImageButton) findViewById(R.id.btn_play_nor);
        mPlayBtn.setOnClickListener(this);

        frangementmanager = getSupportFragmentManager();

        one1 = (ClickImageView) findViewById(R.id.datephoto);
        two1 = (ClickImageView) findViewById(R.id.findphoto);
        three1 = (ClickImageView) findViewById(R.id.messagephoto);
        four1 = (ClickImageView) findViewById(R.id.setphoto);

        one1.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                setTabSelection(0);
            }
        });

        two1.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                setTabSelection(1);
            }
        });

        three1.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                setTabSelection(2);
            }
        });

        four1.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                setTabSelection(3);
            }
        });


        setTabSelection(0);

    }


    void intTablayout() {


        mTabLayout = (TabLayout) findViewById(R.id.mTabLayout);
        mViewPager = (ViewPager) findViewById(R.id.mViewPager);

        mTitle = new ArrayList<>();
        mTitle.add("首页");
        mTitle.add("订阅");
        mTitle.add("发现");
        mTitle.add("我的");

        mIcon = new ArrayList<>();
        mIcon.add(R.drawable.home);
        mIcon.add(R.drawable.subscribe);
        mIcon.add(R.drawable.friend);
        mIcon.add(R.drawable.mine);

        mFragment = new ArrayList<>();
        mFragment.add(new HomepageFragment());
        mFragment.add(new SubscribeFragment());
        mFragment.add(new FriendFragment());
        mFragment.add(new MineFragment());


        mViewPager.setOffscreenPageLimit(mFragment.size());

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {
                    case 0:

                        break;
                    case 1:

                        break;
                    case 3:

                        break;
                    case 4:

                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                return mFragment.get(position);
            }

            @Override
            public int getCount() {
                return mFragment.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle.get(position);
            }

        });

        mTabLayout.setupWithViewPager(mViewPager);

        for (int i = 0; i < mIcon.size(); i++) {
            mTabLayout.getTabAt(i).setIcon(mIcon.get(i));//.setText(mTitle.get(i));
        }
    }


    //选择不同的底部导航
    public void setTabSelection(int index) {

        FragmentTransaction trans = frangementmanager.beginTransaction();
        clearselection();     //清除掉所有选中状态
        hideFragements(trans);    //将所有fragement 置于隐藏状态
        //显示动态内容

        //我的 标题栏颜色切换
//        if (index == 3) {
//            initWindow(true);
//        } else {
//            initWindow(false);
//        }

        switch (index) {
            case 0:
                one1.setSelected(true);


                if (showdate == null) {
                    showdate = new HomepageFragment();
                    trans.add(R.id.content, showdate, "home");
                } else {
                    trans.show(showdate);
                }
                trans.commit();
                break;

            case 1:
                two1.setSelected(true);
                if (showfind == null) {
                    showfind = new SubscribeFragment();
                    trans.add(R.id.content, showfind, "sub");
                } else {
                    trans.show(showfind);
                }
                trans.commit();
                break;
            case 2:
//                three.setTextColor(this.getResources().getColor(R.color.color_tagColor));

                three1.setSelected(true);
                if (showsetup == null) {
                    showsetup = new FriendFragment();
                    trans.add(R.id.content, showsetup, "fri");
                } else {
                    trans.show(showsetup);
                }
                trans.commit();
                break;
            case 3:
//                four.setTextColor(this.getResources().getColor(R.color.color_tagColor));
                four1.setSelected(true);

                if (showmessage == null) {
                    showmessage = new MineFragment();
                    trans.add(R.id.content, showmessage, "mine");
                } else {
                    trans.show(showmessage);
                }
                trans.commit();
                break;

        }
    }

    //清除掉所有的选中状态
    public void clearselection() {
        one1.setSelected(false);
        two1.setSelected(false);
        three1.setSelected(false);
        four1.setSelected(false);

    }

    //将所有fragement 置于隐藏状态
    public void hideFragements(FragmentTransaction transaction) {
        if (showdate != null) {
            transaction.hide(showdate);
        }
        if (showfind != null) {
            transaction.hide(showfind);
        }
        if (showsetup != null) {
            transaction.hide(showsetup);
        }
        if (showmessage != null) {
            transaction.hide(showmessage);
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_play_nor://最新一条播放记录(中间正中间的播放按钮)

                if (BaseApplication.mNewsPlay != null) {
                    VideoPlayerPostModel m = BaseApplication.mNewsPlay;
                    VideoPlayerPostModel model = new VideoPlayerPostModel();
                    model.setMultimedia_id(m.getMultimedia_id());
                    model.setTitle(m.getTitle());
                    model.setIntro(m.getIntro());
                    model.setCover(m.getCover());
                    model.setDuration(m.getDuration());
                    model.setPublish_at(m.getPublish_at());
                    model.setPlay_url(m.getPlay_url());
                    model.setType(m.getType());
                    model.setPlay_count(m.getPlay_count());
                    model.setComment_count(m.getComment_count());
                    model.setLike_count(m.getLike_count());
                    model.setCollection_count(m.getCollection_count());
                    model.setStatus(m.getStatus());
                    model.setCreated_at(m.getCreated_at());
                    model.setUpdated_at(m.getUpdated_at());
                    model.setAlbum_name(m.getAlbum_name());
                    VideoPlayerPostModel.AlbumBean albumBean = new VideoPlayerPostModel.AlbumBean();
                    albumBean.setAlbum_id(m.getAlbum().getAlbum_id());
                    albumBean.setName(m.getAlbum().getName());
                    albumBean.setCover(m.getAlbum().getCover());
                    albumBean.setIs_order(m.getAlbum().getIs_order());
                    model.setAlbum(albumBean);

                    Intent intent = new Intent(this, SubscribeDeteilsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", model);
                    intent.putExtras(bundle);
                    this.startActivity(intent);
                } else {
                    CustomToast.INSTANCE.showToast("暂无播放记录");
                }
                break;
//                    case R.id.datephoto:
//                        setTabSelection(0);
//                        break;
//                    case R.id.findphoto:
//                        setTabSelection(1);
//                        break;
//                    case R.id.messagephoto:
//                        setTabSelection(2);
//                        break;
//                    case R.id.setphoto:
//                        setTabSelection(3);
//                        break;
        }
    }


    public String test() {

        Pools.SimplePool simplePool;


        return "Hlls";
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }



    /**
     * 检查更新
     */
    void checkUpdate() {
        HttpParams params = new HttpParams();
        params.put("platform_type", 1);

        RxVolley.post(StaticClass.APKInfoDes, params, new HttpCallback() {


            @Override
            public void onSuccess(String t) {


                mAPKInfoDesModel = GsonUtils.GsonToBean(t, APKInfoDesModel.class);

                if (mAPKInfoDesModel.getCode() == 200) {

//                    // 获取本版本号，是否更新
                    int vision = UtilTools.getVersion(MainActivity.this);
                    int new_vision = mAPKInfoDesModel.getResult().getVersion_code();
                    ShowDialog(vision, new_vision, mAPKInfoDesModel.getResult().getIs_must_update(), mAPKInfoDesModel.getResult().getDialog_content(), mAPKInfoDesModel.getResult().getDownload_url());
//
//
//                    String str = "4.6.3";
//                    List<String> list = new ArrayList<String>();
//                    list = Arrays.asList(str.split("\\."));
//
//                    for(String s : list){
//                       System.out.println(s);
//                    }


                }
            }

            @Override
            public void onFailure(VolleyError error) {
                super.onFailure(error);
                L.d("error");
            }
        });


    }


    public String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
            // Pattern p2 = Pattern.compile("\\s*\"");
            // Matcher m2 = p2.matcher(dest);
            // dest = m2.replaceAll("\'");
            dest = dest.replace("=\"", "='");
            p = Pattern.compile("\"\0*>");
            m = p.matcher(dest);
            dest = m.replaceAll(">'");
        }
        return dest;
    }

    public String jsonStringConvert(String s) {
        char[] temp = s.toCharArray();
        int n = temp.length;
        for (int i = 0; i < n; i++) {
            if (temp[i] == ':' && temp[i + 1] == '"') {
                for (int j = i + 2; j < n; j++) {
                    if (temp[j] == '"') {
                        if (temp[j + 1] != ',' && temp[j + 1] != '}') {
                            temp[j] = '”';
                        } else if (temp[j + 1] == ',' || temp[j + 1] == '}') {
                            break;
                        }
                    }
                }
            }
        }
        return new String(temp);
    }


    /**
     * @param vision         当前版本
     * @param newversion     新版本
     * @param is_must_update 是否必须更新
     * @param content
     * @param url
     */
    private void ShowDialog(int vision, int newversion, int is_must_update, final String content,
                            final String url) {

        Spanned sp = Html.fromHtml(content.trim().replaceAll(" ", "").toString());


        if (vision < newversion) {

            if (is_must_update == 1) {
                pBar = new CommonProgressDialog(MainActivity.this);
                pBar.setCanceledOnTouchOutside(false);
                pBar.setTitle("正在下载");
                pBar.setCustomTitle(LayoutInflater.from(
                        MainActivity.this).inflate(
                        R.layout.title_dialog, null));
                pBar.setMessage("正在下载");
                pBar.setIndeterminate(true);
                pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pBar.setCancelable(true);
                download(url);
            } else {
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
                builder.setTitle("新版本");
                builder.setMessage(sp);
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        pBar = new CommonProgressDialog(MainActivity.this);
                        pBar.setCanceledOnTouchOutside(false);
                        pBar.setTitle("正在下载");
                        pBar.setCustomTitle(LayoutInflater.from(
                                MainActivity.this).inflate(
                                R.layout.title_dialog, null));
                        pBar.setMessage("正在下载");
                        pBar.setIndeterminate(true);
                        pBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pBar.setCancelable(true);
                        download(url);
                    }
                });
                builder.show();
            }
        } else {
//            CustomToast.INSTANCE.showToast("当前已是最新版");
            return;
        }


    }


    void download(String url) {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
                    pBar.show();

            //下载进度(可选参数，不需要可不传)
            ProgressListener listener = new ProgressListener() {
                @Override
                public void onProgress(long transferredBytes, long totalSize) {
//                    tv.youxing.android.utils.L.d(transferredBytes + "======" + totalSize);
//                    tv.youxing.android.utils.L.d("正在下载:" + transferredBytes * 100 / totalSize
//                            + "%");

                    // transferredBytes 当前下载进度
                    // totalSize 总进度


//                    btnCheck.setText("正在下载:" + transferredBytes * 100 / totalSize
//                            + "%");

                    pBar.setIndeterminate(false);
                    pBar.setMax(100);
                    pBar.setProgress((int) (transferredBytes * 100 / totalSize));
                }
            };

            //下载回调，内置了很多方法，详细请查看源码
            //包括在异步响应的onSuccessInAsync():注不能做UI操作
            //下载成功时的回调onSuccess()
            //下载失败时的回调onFailure():例如无网络，服务器异常等
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onSuccessInAsync(byte[] t) {
                }

                @Override
                public void onSuccess(String t) {


                    pBar.dismiss();

                    CustomToast.INSTANCE.showToast("安装包下载成功");
                    File mFile = new File(Environment.getExternalStorageDirectory().
                            getAbsolutePath() + "/youxing/file/" + "youxing.apk");

                    //判断文件后缀是否是apk
                    if (mFile.getName().endsWith(".apk")) {
                        Intent install = new Intent();
                        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        install.setAction(android.content.Intent.ACTION_VIEW);
                        install.setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive");
                        startActivity(install);
                    }
                }

                @Override
                public void onFailure(int errorNo, String strMsg) {
                    CustomToast.INSTANCE.showToast("更新失败:" + strMsg);
                    L.d("更新失败:" + strMsg);
                }
            };


            RxVolley.download(Environment.getExternalStorageDirectory().
                            getAbsolutePath() + "/youxing/file/" + "youxing.apk",
                    url,
                    listener, callback);

        } else {
            CustomToast.INSTANCE.showToast("没有SD卡");
        }


    }



//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//
//
//        if (requestCode == 555 && resultCode == RESULT_OK && data != null) {
//            List<ImageBean> resultList = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
//
//
//            EventBus.getDefault().post("camera");
//
//            System.out.println("路径是:" + resultList.get(0).getImagePath());
//
//        }
//
//
//        super.onActivityResult(requestCode, resultCode, data);
//    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
